<?php


namespace app\admin\controller;



use cmf\controller\AdminBaseController;
use think\Db;
use think\db\Query;

class SubjectController extends AdminBaseController
{
    //显示
    public  function index(){
        //接收查询条件
        $name = input('subject');

      // halt($school);
        //连接学校表
        $subject=db('subject')
            //搜索查询
            ->where(function (Query $query) use ($name) {
                //模糊查询
                if ($name) {
                    $query->where('subject', 'like', "%$name%");
                }
            })


            //通过id倒序
            ->order('id desc')
            //每页显示3条
            ->paginate('3');
        //halt($school);
        $subject->appends(['name' => $name]);
        //分页
        $page= $subject ->render();
        //渲染模板
        $this->assign('subject',$subject);
        $this->assign('page',$page);

        //映射页面
        return $this->fetch();
    }

    //添加
    public function add(){


        return $this->fetch();
    }

    //将添加数据入库
    public function addpost(){
        //接收数据
        $data= input();
        //halt($data);
        //判断教师名称是否为空
        if (empty($data['subject'])){
                $this->error('科目不能空');
        }

        //添加到数据库
        $add = db('subject')->insert($data);
        if ($add){
            $this->success('添加成功','subject/index');
        }else{
            $this->error('添加失败','subject/index');
        }
    }

    //修改
    public function edit(){
        //接收id
        $id = input('id');
        //通过id搜索该条数据
        $data= db('subject')->get($id);
        //渲染模板
        $this->assign('data',$data);
        //映射页面
        return $this->fetch();
    }
    //保存修改信息
    public function editpost(){
        $data= input();
       // halt($data);
        if (empty($data['subject'])){
            $this->error('科目名称不能空');
        }

        //添加到数据库
        $edit = db('subject')->update($data);
        if ($edit){
            $this->success('修改成功','subject/index');
        }else{
            $this->error('修改失败','subject/index');
        }
    }

    //删除
    public function delete()
    {
        //查询要删除的id
        $id = $this->request->param('id', 0, 'intval');

        //通过id删除该条信息，并判断是否成功
        if (Db::name('subject')->delete($id) !== false) {

            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }

    
}